
from flask import Flask,render_template,url_for,redirect,request,make_response
import utils.csv_util as csv_util
from utils.db_weibo_util import get_all_weibo
from crawler import query_weibo
import time
from crawler.twitter_parase import twitter
from config.config_dynamic import config_dynamic

app = Flask(__name__)

@app.route("/")
def manager_index():
    uids = csv_util.get_weibo_uids()
    twitter_user = csv_util.get_twitter_users()
    at_all = config_dynamic.get('config','enable_atall')
    return render_template('push_index.html',uids=uids,twitter_user=twitter_user,at_all=at_all)

def weibo_sort(elem):
    #转换成时间数组
    timeArray = time.strptime(elem[5], "%Y-%m-%d %H:%M:%S")
    #转换成时间戳
    timestamp = time.mktime(timeArray)
    return timestamp

@app.route('/user/<uid>')
def view_user_weibo(uid):
    weibos = get_all_weibo(uid)
    weibos.sort(key=weibo_sort,reverse=True)
    return render_template('user_weibo_db.html',weibos=weibos)

@app.route('/switch/atall')
def enable_at_all():
    enable = request.args.get('enable','true')
    config_dynamic.set('config','enable_atall',enable)
    return redirect(url_for('manager_index'))

@app.route("/log")
def view_log():
    type = request.args.get('type','crawler')
    path = ''
    if type == 'crawler':
        path = "weibo_dynamic_push.log"
    elif type == 'manager':
        path = "weibo_push_manager.log"
    elif type == 'twitter':
        path = "twitter_dynamic_push.log"
    texts = open(path,'r').readlines()
    texts.reverse()
    result = ""
    for line in texts:
        result+=line
    
    resp = make_response(str(result))
    resp.headers["Content-type"]="application/json;charset=UTF-8"
    return resp

@app.route('/adduser')
def add_user():
    uid = request.args.get('uid','')
    name = query_weibo.get_user_name(uid)
    if(name !=None):
        csv_util.add_user([uid,name])
    return redirect(url_for('manager_index'))

@app.route('/deleteuser/<uid>')
def delete_user(uid=None):
    csv_util.delete_weibo_user(uid)
    return redirect(url_for('manager_index'))


@app.route('/twitter/adduser')
def add_twitter_user():
    uid = request.args.get('uid','')
    name =twitter.get_user_name(uid)
    if(name !=None):
        csv_util.add_twitter_user([uid,name])
    return redirect(url_for('manager_index'))

@app.route('/twitter/deleteuser/<uid>')
def delete_twitter_user(uid=None):
    csv_util.delete_twitter_user(uid)
    return redirect(url_for('manager_index'))


if __name__ == '__main__':
    app.run(host='0.0.0.0',port=80)